package com.zry.yard.retrofit

import android.util.Log

import java.io.IOException

import okhttp3.Call
import okhttp3.Callback
import okhttp3.FormBody
import okhttp3.Request
import okhttp3.Response
import rx.Observable
import rx.Subscriber
import rx.android.schedulers.AndroidSchedulers
import rx.functions.Action1
import rx.schedulers.Schedulers

/**
 * @author ray
 * @date 2018/3/22
 */

interface ApiSupport {
    /**
     * 获取动态API对象
     */
    val api: ApiDynamic
        get() = BaseApiRetrofit().retrofit

    /**
     * 执行动态API调用
     */
    fun <T> execute(api: Observable<T>?, subscriber: Subscriber<T>) {
        if (api == null) {
            RuntimeException("无效API请求").printStackTrace()
            return
        }
        api.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber)
    }

    /**
     * 使用okhttp的GET请求，返回的是字符串
     */
    operator fun get(url: String, callback: Action1<String>) {
        val request = Request.Builder().url(url).build()
        BaseApiRetrofit().okHttpClient.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.e("error", "请求失败$url")
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                callback.call(response.body()!!.string())
            }
        })
    }

    /**
     * 使用okhttp的POST请求
     *
     * @param url      请求地址
     * @param params   请求参数
     * @param callback 请求的回调
     */
    fun post(url: String, params: Map<String, String>, callback: Action1<String>) {
        val body = FormBody.Builder()
        for (key in params.keys) {
            body.add(key, params[key])
        }
        val request = Request.Builder().post(body.build()).url(url).build()
        BaseApiRetrofit().okHttpClient.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.e("error", "请求失败$url")
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                callback.call(response.body()!!.string())
            }
        })
    }

    fun requestError(e: Throwable) {
        e.printStackTrace()
        Log.e("error", e.message)
    }
}
